package com.lambkit.core.loadbalance;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * 加权随机（Weight Random）
 * 利用区间的思想，通过一个小于在此区间范围内的一个随机数，选中对应的区间（服务器），区间越大被选中的概率就越大。
 * @author yangyong
 *
 */
public class WeightRandom {
	
	private Server selectServer(List<Server> serverList) {
		int sumWeight = 0;
		for (Server server : serverList) {
			sumWeight += server.getWeight();
		}
		Random serverSelector = new Random();
		int nextServerRange = serverSelector.nextInt(sumWeight);
		int sum = 0;
		Server selectedServer = null;
		for (Server server : serverList) {
			if (nextServerRange >= sum && nextServerRange < server.getWeight() + sum) {
				selectedServer = server;
			}
			sum += server.getWeight();
		}
		return selectedServer;
	}

	public static void main(String[] args) {
		List<Server> serverList = new ArrayList<>();
		serverList.add(new Server(1, "服务器1", 1));
		serverList.add(new Server(2, "服务器2", 5));
		serverList.add(new Server(3, "服务器3", 10));
		WeightRandom lb = new WeightRandom();
		for (int i = 0; i < 10; i++) {
			Server selectedServer = lb.selectServer(serverList);
			System.out.format("第%d次请求，选择服务器%s\n", i + 1, selectedServer.toString());

		}

	}
}
